<?php 
namespace Admin\Model;
use Think\Model;
class AuthorModel extends Model{

	protected $_validate = array(
		array('authorName','require','歌手名字不能为空'), //默认情况下用正则进行验证
		array('authorIntroduce','require','介绍不能为空'), //默认情况下用正则进行验证
	);
	
	//获取数据
	public function getAll($id=null){
		//为空获取所以数据
		if(is_null($id)){
			$data = $this->select();
			return $data;
		}
		//获取1条数据
		else{
			$data = $this->find($id);
			return $data;
		}
		
	}
	
 
	//添加数据
	public function m_add(){	
		 if($this->create()){
			 //查询是否添加过
			 $name = $_POST['authorName'];
			 $data = $this->where("authorName = '{$name}'")->select();
 
			 if($data){
					$this->error = '添加失败，已有'.$data[0]['authorname'].'id为：'.$data[0]['id'];
			 }else{
				 
				 if(empty($_FILES['authorImg']['name'][0])){
					$this->error ='请添加写真图片';
				}else if(empty($_FILES['authorPic']['name'])){
					$this->error = '请添加头像图片';
				}else{

					$img = $this->upload('authorImg','authorImg','写真上传失败');
					$pic = $this->upload('authorPic','authorPic','头像上传失败');
					//组装post
					$_POST['authorImg'] = json_encode($img);
					$_POST['authorPic'] = $pic[0];
 
					return $this->add($_POST);
					
				}
 
			 }
			 
		 }
	}
	
	//修改数据
	public function edit($id=null){
		if(is_null($id)){
			if($this->create()){
				return $this->save();
			} 
		}else{
			$data = $_POST;
		 
			$fine = $this->where("id={$id}")->save($data);
			return $fine;
		}
		
	}
	
	
	
	//删除数据
	public function del(){
		if($this->where('id='.I('get.id'))->delete()){
			return true;
		}
	}
	
	//删除文件
	public function unnk($data){
		unlink($data);
	}
	
	//封装上传类
	public function upload($name1=null,$name2=null,$txt=null){
		$upload = new \Think\Upload();// 实例化上传类
		// 上传文件 
		$info   =   $upload->upload(array($name1=>$_FILES[$name2]));
		if(!$info) {// 上传错误提示错误信息
				return $this->error = $txt.$upload->getError();
		}else{// 上传成功
			foreach($info as $file){
				$data[]=$upload->rootPath.$file['savepath'].$file['savename'];
			}
			return $data;
		}
	}
}